using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

using System.Windows.Forms;

namespace Darilek.SandcastleExtensions.Utilities
{
	internal class ConfigurationSerializer
	{
		public static T LoadConfiguration<T>(string configuration)
		{
			StringReader reader = new StringReader(configuration);
			XmlSerializer serializer = new XmlSerializer(typeof(T));

			T result = (T)serializer.Deserialize(reader);
			reader.Close();

			return result;
		}

		public static string SaveConfiguration<T>(T configuration)
		{
			XmlSerializer serializer = new XmlSerializer(typeof(T), String.Empty);
			XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces();

			StringWriter writer = new StringWriter();
			serializer.Serialize(writer, configuration, xmlNamespaces);
			string result = writer.ToString();
			writer.Close();
			
			// xml cleanup
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.LoadXml(result);

			foreach (XmlNode node in xmlDoc.ChildNodes)
			{
				// remove <?xml> declaration
				if (node.NodeType == XmlNodeType.XmlDeclaration)
				{
					xmlDoc.RemoveChild(node);
				}
			}

			// remove xmlns attributes
			List<XmlAttribute> attributes = new List<XmlAttribute>();
			foreach (XmlAttribute attribute in xmlDoc.DocumentElement.Attributes)
			{
				if (attribute.Name.ToLower().StartsWith("xmlns"))
					attributes.Add(attribute);
			}

			attributes.ForEach(delegate(XmlAttribute attribute) { xmlDoc.DocumentElement.Attributes.Remove(attribute); });

			result = xmlDoc.InnerXml;
			
			return result;

		}
	}
}
